const config = require('../../util/config')
const logger = require('log4js').getLogger()

async function loginTaobao(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    if (obj.step !== 0) {
        logger.debug('[' + __filename + ':' + __line + ']', 'logining taobao', JSON.stringify(obj))
        obj.step = 0
    }
    try {
        await Page.navigate({
            url: 'https://pub.alimama.com/index.htm'
        })
        return step1.call(this, obj)
    } catch (err) {
        logger.error('[' + __filename + ':' + __line + ']', err)
        logger.error('[' + __filename + ':' + __line + ']', err.code)
        logger.error('[' + __filename + ':' + __line + ']', err.message)
        this.connect()
        return Promise.reject(err)
    }
}

async function step1(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
        if (obj.times > config.chromeMaxTimes) {
            return new Promise((resolve, reject) => {
                reject('登录淘宝联盟超时，访问https://pub.alimama.com/index.htm慢')
            })
        }
    if (obj.step !== 1) {
        logger.debug('[' + __filename + ':' + __line + ']', 'logining taobao step 1', JSON.stringify(obj))
        obj.step = 1
    }
    try {
        var { result } = await Runtime.evaluate({ expression: 'location.href' })
        if (result.value == 'https://pub.alimama.com/index.htm') {
            return step2.call(this, obj)
        }
        if (obj.times == Math.floor(config.chromeMaxTimes / 2)) {
            return loginTaobao.call(this, obj)
        } else {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    step1.call(this, obj).then(result => {
                        resolve(result)
                    }, result => {
                        reject(result)
                    })
                }, 1000)
            })
        }
    } catch (err) {
        log(err)
    }
}

async function step2(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
        if (obj.times > config.chromeMaxTimes) {
            return new Promise((resolve, reject) => {
                reject(this.username + '登录淘宝联盟超时，等待扫码')
            })
        }
    if (obj.step !== 2) {
        logger.debug('[' + __filename + ':' + __line + ']', 'logining taobao step 2', JSON.stringify(obj))
        obj.step = 2
    }
    try {
        var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("div.bokmXvjEkM.text-center.mb10")' })
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt != 0) {
            return new Promise(resolve => {
                this.store({ qrcode: '' })
                resolve()
            })
        }
        var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")' })
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt == 0) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    step2.call(this, obj).then(result => {
                        resolve(result)
                    }, result => {
                        reject(result)
                    })
                }, 1000)
            })
        }
        if (cnt != 2) {
            var useQrcode = true
                // var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("iframe")'})
                // var cnt = result.description.substring(9, result.description.length - 1)
                // if (cnt == 1) {//不用短信验证码
                //   var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#nocaptcha")'})
                //   var cnt = result.description.substring(9, result.description.length - 1)
                //   if (cnt == 0) {
                //     return new Promise(resolve => {
                //       setTimeout(() => {
                //         resolve(checkLogin(client))
                //       }, 1000)
                //     })
                //   }
                //   var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#nocaptcha")[0].style.display'})
                //   if (result.value == '') {//不用滑块，用户名密码登录
                //     var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("div#J_LoginBox")[0].className'})
                //     if (result.value.indexOf('module-quick') != -1) {
                //       await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_Static2Quick")[0].click()'})
                //     }
                //     await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#TPL_username_1")[0].value="jun_1222"'})
                //     await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#TPL_password_1")[0].value="yoyo@9876"'})
                //     await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_SubmitStatic")[0].click()'})
                //     useQrcode = true
                //   }
                // }
            if (useQrcode) {
                var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")' })
                var cnt = result.description.substring(9, result.description.length - 1)
                if (cnt == 0) {
                    logger.debug('[' + __filename + ':' + __line + ']', 'document.querySelectorAll("iframe[name=taobaoLoginIfr]").length == 0')
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            step2.call(this, obj).then(result => {
                                resolve(result)
                            }, result => {
                                reject(result)
                            })
                        }, 1000)
                    })
                }
                var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("div#J_LoginBox")' })
                var cnt = result.description.substring(9, result.description.length - 1)
                if (cnt == 0) {
                    logger.debug('[' + __filename + ':' + __line + ']', 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("div#J_LoginBox").length == 0')
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            step2.call(this, obj).then(result => {
                                resolve(result)
                            }, result => {
                                reject(result)
                            })
                        }, 1000)
                    })
                }
                var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("div#J_LoginBox")[0].className' })
                if (!result.value || result.value.indexOf('module-quick') == -1) {
                    await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_Static2Quick")[0].click()' })
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            step2.call(this, obj).then(result => {
                                resolve(result)
                            }, result => {
                                reject(result)
                            })
                        }, 1000)
                    })
                }
                var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("div#J_QRCodeLogin")[0].className' })
                if (!result.value || result.value.indexOf('qrcode-login-error') != -1) {
                    await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("a.refresh.J_QRCodeRefresh")[0].click()' })
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            step2.call(this, obj).then(result => {
                                resolve(result)
                            }, result => {
                                reject(result)
                            })
                        }, 1000)
                    })
                }
                var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_AkeyLogin")' })
                var cnt = result.description.substring(9, result.description.length - 1)
                if (cnt != 0) {
                    var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_AkeyLogin")[0].style.display' })
                    if (result.value == 'block') {
                        var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_AkeyLogin")[0].className' })
                        if (result.value.indexOf('akey-login-ok') == -1) {
                            await Runtime.evaluate({ expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")[0].contentDocument.querySelectorAll("#J_AkeyLogin button")[0].click()' })
                                //log('here')
                            return new Promise((resolve, reject) => {
                                setTimeout(() => {
                                    step2.call(this, obj).then(result => {
                                        resolve(result)
                                    }, result => {
                                        reject(result)
                                    })
                                }, 1000)
                            })
                        }
                    }
                }
            }
        }
        //log('here')
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step2.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    } catch (err) {
        logger.error('[' + __filename + ':' + __line + ']', err)
        reject()
    }
}

module.exports = loginTaobao